package com.shawn.gateway.fiter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shawn.commons.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
//@Order(-1)//优先执行
@Component//交由IOC容器
public class AuthorizeFilter implements GlobalFilter , Ordered {
    @Value("${gateway.excludedUrls}")
    private ArrayList<String> excludeUrls;//从yml配置文件中,读取不需要鉴权的请求
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //排除掉需要放行的路径
        String path = exchange.getRequest().getURI().getPath();
        log.info("拦截到路径:{}",path);
        if (excludeUrls.contains(path)){
            //如果包含直接放行
            return chain.filter(exchange);
        }
        //获取token完成鉴权
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        //后台系统页面发送的token以"Bearer "开头，需要处理
        if(!StringUtils.isEmpty(token)){
            token = token.replace("Bearer ", "");
        }
        ServerHttpResponse response = exchange.getResponse();

        //token处理
        boolean verifyToken = JwtUtils.verifyToken(token);
        if (!verifyToken){
            //响应错误码
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("errCode", 401);
            responseData.put("errMessage", "用户未登录");
            return responseError(response,responseData);
        }
        return chain.filter(exchange);
    }
    //响应错误数据
    private Mono<Void> responseError(ServerHttpResponse response,Map<String, Object> responseData){
        // 将信息转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] data = new byte[0];
        try {
            data = objectMapper.writeValueAsBytes(responseData);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        // 输出错误信息到页面
        DataBuffer buffer = response.bufferFactory().wrap(data);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    /*配置过滤器执行顺序,低优先级*/
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
